<template>
  <Card class="m-2 border-0">
    <div class="flex">
      <Card class="!w-96 mr-4" title="用户信息">
        <ul class="user-info">
          <li>
            <Space>
              <UserOutlined />
              <span>用户名称</span>
            </Space>
            <span>{{ userInfo.userName }}</span>
          </li>
          <li>
            <Space>
              <ShakeOutlined />
              <span>手机号码</span>
            </Space>
            <span>{{ userInfo.phonenumber }}</span>
          </li>
          <li>
            <Space>
              <MailOutlined />
              <span>用户邮箱</span>
            </Space>
            <span>{{ userInfo.email }}</span>
          </li>
          <li>
            <Space>
              <ApartmentOutlined />
              <span>所属部门</span>
            </Space>
            <span>{{ userInfo.dept?.deptName || '' }}/{{ postGroup }}</span>
          </li>
          <li>
            <Space>
              <UsergroupDeleteOutlined />
              <span>所属角色</span>
            </Space>
            <span>{{ roleGroup }}</span>
          </li>
          <li>
            <Space>
              <FieldTimeOutlined />
              <span>创建日期</span>
            </Space>
            <span>{{ userInfo.userName }}</span>
          </li>
        </ul>
      </Card>
      <Card
        class="!w-full overflow-hidden"
        :tab-list="tabs"
        :active-tab-key="currentTab"
        @tab-change="(e) => onTabChange(e)"
      >
        <ProForm
          ref="formRef"
          :items="items"
          show-submit-button
          :label-col="{ span: 2 }"
          :wrapper-col="{ span: 12 }"
          :model="formModel"
          @submit="onSubmit"
          @cancel="onCancel"
        >
          <template #wx>
            <div v-show="wxBindInfo.userName">
              <span class="mx-2">{{ wxBindInfo.wxUserId }}</span>
              <Button @click="cancelBind">解除绑定</Button>
            </div>
            <div v-show="!wxBindInfo.userName" id="ww_login"></div>
          </template>
        </ProForm>
      </Card>
    </div>
  </Card>
  <Modal v-model:open="open" centered title="密码验证" @ok="onMoadlSubmit">
    <Form :model="formState">
      <FormItem
        label="登录密码"
        name="password"
        sh
        :rules="[{ required: true, message: '请输入登录密码' }]"
      >
        <InputPassword
          v-model:value="formState.password"
          placeholder="请输入登录密码"
        />
      </FormItem>
    </Form>
  </Modal>
</template>

<script setup lang="tsx">
import { computed, nextTick, onMounted, reactive, ref } from 'vue';
import {
  ApartmentOutlined,
  FieldTimeOutlined,
  MailOutlined,
  ShakeOutlined,
  UserOutlined,
  UsergroupDeleteOutlined,
} from '@ant-design/icons-vue';
import * as ww from '@wecom/jssdk';
import {
  Button,
  Card,
  CardProps,
  ConfigProvider,
  Flex,
  Form,
  FormItem,
  Image,
  InputPassword,
  Modal,
  Space,
  message,
} from 'ant-design-vue';
import { useRouter } from 'vue-router';
import { ProForm, ProFormProps } from '@/components/ProForm/index';
import { isEmptyObject } from '@/utils/utils';
import {
  bindqwWeiXinUser,
  cancelBindUser,
  fetchUserInfo,
  fetchWeiXinBindUser,
  generateWeiXinQrCode,
  updatePassword,
  updateUserInfo,
  wxUserInfo,
} from '@/api/system';

const router = useRouter();
const formRef = ref();
const formModel = ref({
  nickName: '',
  phonenumber: '',
  email: '',
  sex: '',
});
const open = ref(false);
const roleGroup = ref('');
const postGroup = ref('');
const formState = reactive({
  password: '',
});
const userInfo = ref<Record<string, any>>({});
const wxBindInfo = ref<Record<string, any>>({});
const imgBase64 = ref('');
const init = async () => {
  const res = await fetchUserInfo();
  // @ts-ignore
  userInfo.value = res.data;
  // @ts-ignore
  roleGroup.value = res.roleGroup;
  // @ts-ignore
  postGroup.value = res.postGroup;

  const { nickName, phonenumber, email, sex } = res.data as any;
  const data = {
    nickName,
    phonenumber,
    email,
    sex,
  };

  const resWx = await wxBindUserInfo();
  if (!isEmptyObject(resWx as Record<string, any>)) {
    wxBindInfo.value = resWx as any;
  } else {
    await nextTick();
    initWxQsCode();
  }
  for (const key in data) {
    if (Object.prototype.hasOwnProperty.call(data, key)) {
      formRef.value.setFiledValue(key, data[key as keyof typeof data]);
    }
  }
};
onMounted(init);

const wxUserId = ref('');
const wxBindUserInfo = async () => {
  const res = await fetchWeiXinBindUser({
    userName: userInfo.value.userName,
  });
  return res.data;
};
const initWxQsCode = () => {
  const wxScan = ww.createWWLoginPanel({
    el: '#ww_login',
    params: {
      login_type: 'CorpApp' as any,
      appid: 'ww718df1b020104c42',
      agentid: '1000005',
      redirect_uri: 'http://ims.demo.boeyo.com:81/personal',
      state: 'bindState',
      panel_size: 'small' as any,
      redirect_type: 'callback' as any,
    },
    onLoginSuccess({ code }) {
      console.log({ code });
      wxUserInfo({ code }).then((res) => {
        console.log(res);
        if (res.code == 200) {
          open.value = true;
          wxUserId.value = (res.data as { userId: string }).userId;
        }
      });
    },
    onLoginFail(err) {
      console.log(err);
    },
  });
};
// const onMoadlSubmit = async () => {
//   wxUserInfo({
//     userName: userInfo.value.userName,
//     password: formState.password,
//     ...params.value,
//   }).then((res) => {
//     console.log(res);
//     if (res.code == 200) {
//       wxUserId.value = (res.data as { userId: string }).userId;
//       bindqwWeiXinUser({
//         userName: userInfo.value.userName,
//         wxUserId: wxUserId.value,
//         password: formState.password,
//       }).then((res) => {
//         if (res.code === 200) {
//           window.location.reload();
//           message.success('绑定成功');
//         } else {
//           message.error((res as any).message);
//         }
//       });
//     }
//   });
// };
const onMoadlSubmit = async () => {
  bindqwWeiXinUser({
    userName: userInfo.value.userName,
    wxUserId: wxUserId.value,
    password: formState.password,
  }).then((res) => {
    if (res.code === 200) {
      window.location.reload();
      message.success('绑定成功');
    } else {
      message.error((res as any).message);
    }
    open.value = false;
  });
};
const serviceApi = computed(() =>
  currentTab.value === '1' ? updateUserInfo : updatePassword,
);

const onSubmit = async (data: any) => {
  const params =
    currentTab.value === '1'
      ? { ...data, userId: userInfo.value.userId }
      : data;
  await serviceApi.value(params);
  message.success('修改成功');
};

const currentTab = ref('1');
const onCancel = () => {
  router.go(-1);
};

const tabs: CardProps['tabList'] = [
  {
    tab: '基本资料',
    key: '1',
  },
  {
    tab: '修改密码',
    key: '2',
  },
];

const onTabChange = async (key: string) => {
  currentTab.value = key;
  if (key === '1') {
    if (!wxBindInfo.value.userName) {
      await nextTick(); // 等待 DOM 更新完成
      initWxQsCode();
    }
  }
};
const items = computed<ProFormProps['items']>(() => {
  if (currentTab.value === '1') {
    return [
      {
        label: '用户昵称',
        type: 'input',
        field: 'nickName',
        rules: [{ required: true, message: '请输入用户昵称', trigger: 'blur' }],
        props: {},
      },

      {
        label: '手机号码',
        type: 'input',
        field: 'phonenumber',
        rules: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
        props: {},
      },
      {
        label: '邮箱',
        type: 'input',
        field: 'email',
        rules: [
          {
            required: true,
            message: '请输入正确的邮箱地址',
            trigger: 'blur',
            type: 'email',
          },
        ],
        props: {},
      },
      {
        label: '企微账号',
        type: 'button',
        field: 'wx',
      },
      {
        label: '性别',
        type: 'radio',
        field: 'sex',
        props: {
          options: [
            { label: '男', value: '0' },
            { label: '女', value: '1' },
          ],
        },
      },
    ] as ProFormProps['items'];
  } else {
    return [
      {
        label: '旧密码',
        type: 'input',
        field: 'oldPassword',
        rules: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
        props: {
          type: 'password',
        },
      },
      {
        label: '新密码',
        type: 'input',
        field: 'newPassword',
        rules: [
          {
            required: true,
            trigger: 'blur',
            message: '请输入密码，切不少于8位字符',
            type: 'string',
            min: 8,
          },
          {
            trigger: 'blur',
            validator(rule, value) {
              if (
                /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]/.test(
                  value,
                )
              ) {
                return Promise.resolve();
              } else {
                return Promise.reject(
                  '密码至少包含大写字母、小写字母、数字和特殊字符中的 3 种',
                );
              }
            },
          },
        ],
        props: {
          type: 'password',
        },
      },
      {
        label: '确认密码',
        type: 'input',
        field: 'checkPassword',
        rules: [
          {
            required: true,
            trigger: 'blur',
            validator(rule, value) {
              if (formRef.value.getFieldsValue().newPassword !== value)
                return Promise.reject('两次输入密码不一致');
              return Promise.resolve();
            },
          },
        ],

        props: {
          type: 'password',
        },
      },
    ] as ProFormProps['items'];
  }
});
const cancelBind = () => {
  cancelBindUser({
    ...wxBindInfo.value,
  }).then(() => {
    wxBindInfo.value = {};
    initWxQsCode();
    message.success('解除绑定成功');
  });
};
</script>

<style lang="scss" scoped>
.user-info {
  li {
    height: 48px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px dashed rgba(255, 255, 255, 0.3);
  }
}
</style>
